package com.lucy.rabc.service.impl;

import com.lucy.rabc.dao.SysRoleMenuDAO;
import com.lucy.rabc.entity.SysRoleMenu;
import com.lucy.rabc.service.SysRoleMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kindear
 */
@Slf4j
@Service
public class SysRoleMenuServiceImpl implements SysRoleMenuService {
    @Autowired
    SysRoleMenuDAO dao;

    @Override
    public List<Long> getRoleMenuIds(Long roleId) {
        List<SysRoleMenu> roleMenus =  dao.findByRoleId(roleId);
        return roleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
    }

    @Override
    public List<Long> getRolesMenuIds(List<Long> roleIds) {
        List<SysRoleMenu> roleMenus =  dao.findByRoleIdIn(roleIds);
        return roleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void deleteByRoleId(Long roleId) {
        dao.deleteByRoleId(roleId);
    }

    @Override
    @Transactional
    public List<SysRoleMenu> batchSetRoleMenus(Long roleId, List<Long> menuIds) {
        deleteByRoleId(roleId);
        List<SysRoleMenu> addTasks = new ArrayList<>();
        for (Long menuId : menuIds) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(menuId);
            addTasks.add(sysRoleMenu);
        }
        return dao.saveAll(addTasks);
    }
}
